package com.lanou.dllo.soccernews.fragment.deepfragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.dllo.myrecycler.AnimRFRecyclerView;
import com.lanou.dllo.myrecycler.AnimRFStaggeredGridLayoutManager;
import com.lanou.dllo.soccernews.R;
import com.lanou.dllo.soccernews.adapter.DeepAdapter;
import com.lanou.dllo.soccernews.bean.DeepBean;
import com.lanou.dllo.soccernews.bean.greendao.DeepBeanArticlesEntity;
import com.lanou.dllo.soccernews.database.DeepHelp;
import com.lanou.dllo.soccernews.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/26.
 */
public class DeepFragment extends Fragment {
    private AnimRFRecyclerView mRecyclerView;
    private View headerView;
    private View footerView;
    //数据
    private List<DeepBeanArticlesEntity> articles;
    private Handler mHandler = new Handler();
    private List<Integer> heights = new ArrayList<>();
    private Context mContext;
    private DeepAdapter deepAdapter;
    private DeepHelp help = DeepHelp.getInstance();

    private VolleySingleton volleySingleton = VolleySingleton.getInstance();
    ;

    public DeepFragment() {
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRecyclerView == null) {


            mContext = getActivity();
            mRecyclerView = new AnimRFRecyclerView(mContext);
            headerView = LayoutInflater.from(mContext).inflate(R.layout.header_view, null);

            footerView = LayoutInflater.from(mContext).inflate(R.layout.footer_view, null);
            //使用重写后的去不留布局管理器
            mRecyclerView.setLayoutManager(new AnimRFStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
            //添加头部和脚步,
            mRecyclerView.addHeaderView(headerView);
            //设置头部的最大拉伸倍率,默认1.5f,必须写在setHeaderImage()之前
            mRecyclerView.setScaleRatio(1.7f);
            //设置下拉时拉伸的图片 ,不设置就使用默认
            mRecyclerView.setHeaderImage((ImageView) headerView.findViewById(R.id.iv_hander));
            mRecyclerView.addFootView(footerView);
            //设置涮新动画的颜色
            mRecyclerView.setColor(Color.GREEN, Color.RED);
            //设置头部回复动画的执行时间,默认为1000毫秒
            mRecyclerView.setHeaderImageDurationMillis(1200);
            // 设置拉伸到最高时头部的透明度，默认0.5f
            mRecyclerView.setHeaderImageMinAlpha(0.6f);


            //设置适配器
            deepAdapter = new DeepAdapter(heights);
            mRecyclerView.setAdapter(deepAdapter);

            //设置刷新和加载更多数据的监听分别在onRefresh () 和onLoadMore()方法中执行刷新和加载跟多操作

//            mRecyclerView.setLoadDataListener(new AnimRFRecyclerView.LoadDataListener() {
//                @Override
//                public void onRefresh() {
//                    new Thread(new MyRunnable(true)).start();
//                }
//
//                @Override
//                public void onLoadMore() {
//                    new Thread(new MyRunnable(false)).start();
//                }
//            });

        }
        return mRecyclerView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        articles = help.getArticlesEntity();
        if (articles != null && articles.size() > 0) {
            deepAdapter.addData(articles);

            for (int i = 0; i < 20; i++) {
                calHeight();
            }
        } else {
            addData();
        }


    }

//    class MyRunnable implements Runnable {
//        boolean isRefresh;
//
//        public MyRunnable(boolean isRefresh) {
//            this.isRefresh = isRefresh;
//        }
//
//        @Override
//        public void run() {
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            mHandler.post(new Runnable() {
//                @Override
//                public void run() {
//                    if (isRefresh) {
//                        newData();
//                        mRecyclerView.refreshComplate();
//                    } else {
//                        addData();
//                        loadMoreComplate();
//                        mRecyclerView.loadMoreComplate();
//                    }
//                }
//            });
//        }
//    }

//    public void refreshComplate() {
//        mRecyclerView.getAdapter().notifyDataSetChanged();
//    }

//    public void loadMoreComplate() {
//         /*
//         * 用notifyDataSetChanged()的话，加载完重新滚动到顶部的时候会产生错位并自动调整布局，
//         * 所以用requestLayout()刷新布局
//         */
//        // mRecyclerView.getAdapter().notifyDataSetChanged();
//        mRecyclerView.requestLayout();
//
//    }

    //添加数据

    private void addData() {
        String url = "https://api.dongqiudi.com/tabs_static/2/iphone/55.json";
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        DeepBean deepBean = gson.fromJson(response, DeepBean.class);
                        if (deepBean != null) {
                            articles = deepBean.getArticles();


                            if (articles != null && articles.size() > 0) {
                                //   Log.i("lanou", articles + "hhhhhhhhhhhhhhhh");
                                deepAdapter.addData(articles);
                                help.addArticlesEntity(articles);
                            }
                        }
                        for (int i = 0; i < 20; i++) {
                            calHeight();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        volleySingleton.addRequest(request);
    }

    public void newData() {
        articles.clear();
        heights.clear();
        for (int i = 0; i < 20; i++) {
            // articlesEntities.add("刷新后条目  " + (articlesEntities.size() + 1));
            calHeight();
        }
    }

    public void calHeight() {
        double d = Math.random();
        if (d < 0.25) {
            heights.add(DimensionConvert.dip2px(mContext == null ? getActivity() : mContext, 90));
        } else if (d < 0.5) {
            heights.add(DimensionConvert.dip2px(mContext == null ? getActivity() : mContext, 110));
        } else if (d < 0.75) {
            heights.add(DimensionConvert.dip2px(mContext == null ? getActivity() : mContext, 130));
        } else {
            heights.add(DimensionConvert.dip2px(mContext == null ? getActivity() : mContext, 100));
        }
    }

}
